/**
 * @Author: ls <ls-mac>
 * @Date:   2018-10-11 15:54:09
 * @Last modified by:   ls-mac
 * @Last modified time: 2020-07-02 20:03:50
 */

import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { loginService, logout } from 'services/login';

export default {
  namespace: 'login',

  state: {
    status: undefined,
    currentUser: {},
  },

  effects: {
    *login({ payload, callback }, { call, put }) {
      const response = yield call(loginService, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });

      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });

      if (callback) {
        callback(response);
      }
    },
    *logout(_, { call, put }) {
      yield call(logout);
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      // reloadAuthorized();
      yield put(
        routerRedux.push({
          pathname: '/login',
        })
      );
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      sessionStorage.setItem('login-resources', '');
      localStorage.setItem('authorization-token', '');
      localStorage.setItem('currentUser', '');
      return {
        ...state,
      };
    },
    saveCurrentUser(state, { payload }) {
      const {
        data: { currentUser },
      } = payload;
      localStorage.setItem('currentUser', JSON.stringify(currentUser));
      return {
        ...state,
        currentUser,
      };
    },
  },
};
